#include "widget.h"
#include "ui_widget.h"
#include "config.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_ip_Button_clicked()
{
    client = new QMqttClient;
    //绑定连接成功信号
    connect(client, &QMqttClient::connected, this, &Widget::connectSuccess);
    connect(client, &QMqttClient::disconnected, this, &Widget::connectError);
    //绑定连接的ip
    client->setHostname(MQTT_HOSTNAME);
    //绑定端口
    client->setPort(MQTT_PORT);
    //连接服务器
    client->connectToHost();
}

void Widget::connectSuccess()
{
    QMessageBox::about(this, "提示", "连接成功");
}

void Widget::connectError()
{
    QMessageBox::about(this, "提示", "连接失败");
}

void Widget::on_sub_Button_clicked()
{
    //订阅主题
    client->subscribe(ui->sub_lineEdit->text());
    //绑定信号与槽，当收到消息后调用槽函数
    connect(client, &QMqttClient::messageReceived, this, &Widget::Receive);
}

void Widget::Receive(QByteArray buf)
{
    ui->textEdit->append(QString(buf));
}

void Widget::on_pub_Button_clicked()
{
    //发布消息，主题为pub_lineEdit
    client->publish(ui->pub_lineEdit->text(), ui->text_lineEdit->text().toLatin1());
}

void Widget::on_clear_Button_clicked()
{
    ui->textEdit->clear();
}
